package com.lyl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyl.domain.SysUser;
import com.lyl.domain.SysUserRole;
import com.lyl.mapper.SysUserMapper;
import com.lyl.service.SysUserRoleService;
import com.lyl.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author lylbell
 * @date 2021-06-22 13:31
 */
    
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 通过分页查询员工数据
     *
     * @param page
     * @param mobile
     * @param fullname
     * @return
     */
    @Override
    public Page<SysUser> findByPage(Page<SysUser> page, String mobile, String fullname) {
        Page<SysUser> userPage = page(page, new LambdaQueryWrapper<SysUser>().like(!StringUtils.isEmpty(mobile),SysUser::getMobile, mobile)
                .like(!StringUtils.isEmpty(fullname),SysUser::getFullname, fullname));
        List<SysUser> records = userPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (SysUser record : records) {
                List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, record.getId()));
                String collect = list.stream().map(sysUserRole -> sysUserRole.getRoleId().toString()).collect(Collectors.joining(","));
                record.setRole_strings(collect);
            }
        }
        return userPage;
    }

    /**
     * 保存员工信息
     *
     * @param sysUser
     * @return
     */
    @Transactional
    @Override
    public boolean saveUser(SysUser sysUser) {
        //1.将密码进行加密
        String password = sysUser.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodePassword = bCryptPasswordEncoder.encode(password);
        sysUser.setPassword(encodePassword);
        boolean save = sysUserService.save(sysUser);
        if (save) {
            List<SysUserRole> list = new ArrayList<>();
            //2.添加员工成功，将角色信息添加到用户角色表
            //注：要判断一下是否有角色，有的话才split。前端有校验，一定要选择一个角色
            String[] split = sysUser.getRole_strings().split(","); //将角色信息用，分隔开
            for (String roleId : split) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(Long.valueOf(roleId));
                list.add(sysUserRole);
            }
            return sysUserRoleService.saveBatch(list);
        }
        return false;
    }

    /**
     * 修改员工信息
     *
     * @param sysUser
     * @return
     */
    @Transactional
    @Override
    public Boolean updateUser(SysUser sysUser) {
        SysUser user = sysUserService.getById(sysUser.getId());
        if (user.getPassword() != sysUser.getPassword()) {  //如果数据库密码和用户传来的密码不匹配去，说明用户修改了密码，此时需要重新加密
            String encodePassword = new BCryptPasswordEncoder().encode(sysUser.getPassword());
            sysUser.setPassword(encodePassword);
        }
        boolean update = sysUserService.updateById(sysUser);
        if (!update) {
            return false;
        }
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,sysUser.getId()));
        String[] split = sysUser.getRole_strings().split(",");
        List<SysUserRole> list = new ArrayList<>();
        for (String roleId : split) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(Long.valueOf(roleId));
            list.add(sysUserRole);
        }
        return sysUserRoleService.saveBatch(list);
    }

    /**
     * 删除员工信息
     *
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public boolean removeUsers(String[] ids) {
        boolean delete = super.removeByIds(Arrays.asList(ids));
        if (delete) {
            return sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, Arrays.asList(ids)));
        }
        return false;
    }
}
